package com.example.javaee.service;

import com.example.javaee.Util.CommunityUtil;
import com.example.javaee.dao.UserMapper;
import com.example.javaee.domain.User;
import com.example.javaee.exception.UserAdminException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    LoginService loginService;

    Logger logger = LoggerFactory.getLogger(getClass());

    public void updateUserInfo(Integer userId, User info) throws UserAdminException
    {

        User user = userMapper.selectById(userId);
        if(user == null)
        {
            throw new UserAdminException(
                    "该用户不存在!");
        }
        try
        {
            info.setId(user.getId());
            userMapper.updateUserInfo(info);
        }
        catch (Exception e)
        {
            throw new UserAdminException("用户信息更新失败！");
        }
    }
    public void updatePassword(String oldPassword, String newPassword) throws UserAdminException
    {
        Integer userId = loginService.getLoginUser().getId();
        User user = userMapper.selectById(userId);
        if(user == null)
        {
            throw new UserAdminException(
                    "该用户不存在!");
        }
        String str = CommunityUtil.md5(oldPassword+ user.getSalt());
        logger.info("oldPassword :" + str);
        logger.info("usrPassword :" + user.getPassword());
        if(user.getPassword().equals(str))
        {
            try
            {
                user.setPassword(CommunityUtil.md5(newPassword+ user.getSalt()));
                userMapper.updateUserPassword(user);
            }
            catch (Exception e)
            {
                throw new UserAdminException("更改密码失败!");
            }
        }
        else {
            throw new UserAdminException("旧密码不正确!");
        }
    }

    public List<User> getAllUsers(){
        List<User> result = new ArrayList<>();
        result = userMapper.selectList(null);
        return result;
    }

    public void deleteUser(Integer id) {
        userMapper.deleteById(id);
    }
}
